//
//  ChatListViewController.m
//  EasyToTesco2.0
//
//  Created by knew on 2017/1/5.
//  Copyright © 2017年 EasyToTesco. All rights reserved.
//

#import "ChatListViewController.h"

#import "ChatViewController.h"
#import "ChatDemoHelper.h"

#define kHaveUnreadAtMessage    @"kHaveAtMessage"
#define kAtYouMessage           1
#define kAtAllMessage           2

@interface ChatListViewController ()<EaseConversationListViewControllerDelegate, EaseConversationListViewControllerDataSource,EMClientDelegate>

{
    NSString *_userName;
    UIImageView *noDrawImage;
}

@property (nonatomic, strong) UIView *networkStateView;


@end

@implementation ChatListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self tableViewDidTriggerHeaderRefresh];
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOCATIONNOTICATION object:@"string"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_JUDGESHOWALERT object:@"string"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"JudgeShowOrDissMissAlert" object:@"string"];
    
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    
    if (!conversations.count) {
        noDrawImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_NoRecord"]];
        [self.view addSubview:noDrawImage];
        self.tableView.backgroundColor = BACKGROUND_COLOR;
        
        [noDrawImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX);
            make.centerY.equalTo(self.view.mas_centerY).offset(-HEIGHT/8);
            make.width.mas_equalTo(WIDTH/1.5);
            make.height.mas_equalTo(WIDTH/2.4);
        }];
    } else {
        self.showRefreshHeader = YES;
        self.delegate = self;
        self.dataSource = self;
    }}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOCATIONNOTICATION object:@""];
}

- (void)dealloc {
    [[EMClient sharedClient] removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNOTIFICATION_LOCATIONNOTICATION object:@"string"];
    
}

- (void)userAccountDidLoginFromOtherDevice {
//    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshDataSource];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [[ChatDemoHelper shareHelper].mainVC setupUnreadMessageCount];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, -25, 0, 0)];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)removeEmptyConversationsFromDB
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (!conversation.latestMessage || (conversation.type == EMConversationTypeChatRoom)) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            [needRemoveConversations addObject:conversation];
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EMClient sharedClient].chatManager deleteConversations:needRemoveConversations isDeleteMessages:YES completion:nil];
    }
}

#pragma mark - getter

- (UIView *)networkStateView
{
    if (_networkStateView == nil) {
        _networkStateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 44)];
        _networkStateView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:199 / 255.0 blue:199 / 255.0 alpha:0.5];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (_networkStateView.frame.size.height - 20) / 2, 20, 20)];
        imageView.image = [UIImage imageNamed:@"messageSendFail"];
        [_networkStateView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 5, 0, _networkStateView.frame.size.width - (CGRectGetMaxX(imageView.frame) + 15), _networkStateView.frame.size.height)];
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = [UIColor grayColor];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"当前网络连接失败", @"Network disconnection");
        [_networkStateView addSubview:label];
    }
    
    return _networkStateView;
}

- (void)didReceiveMessages:(NSArray *)aMessages {
    NSLog(@"%s",__func__);
    
    [self refreshDataSource];
}

- (void)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
            didSelectConversationModel:(id<IConversationModel>)conversationModel
{
    [self showHudInView:self.view hint:nil];
    if (conversationModel) {
        EMConversation *conversation = conversationModel.conversation;
        if (conversation) {
            NSLog(@"%@",conversationModel.title);
            
            NSDictionary *params = @{
                                     @"username":conversationModel.title
                                     };
            
            [[NetWorkSharedTools sharedNetWorkTools] GetObjectWithURLDict:params AndMenthodName:@"/api/Chat/memberInfo" completeBlock:^(id object) {
                NSLog(@"%@",object);
                [self hideHud];
                if (JudgeBackDataCode) {
                    NSDictionary *dict = [object objectForKey:@"data"];
                    SellerUserInfoModel *infoModel = [[SellerUserInfoModel alloc] initWithDictionary:dict error:nil];
                    
                    ChatViewController *chat = [[ChatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
                    
                    chat.FromSellerNumber = conversationModel.title;
                    if (infoModel.member_name.length) {
                        chat.title = infoModel.member_name;
                    } else {
                        chat.title = conversationModel.title;
                    }
                    [self.navigationController pushForm:self.navigationController pushToAndHidden:chat];
                    
                } else {
                    [self showHint:[NSString stringWithFormat:@"%@",[object[@"message"] objectForKey:@"msg"]]];
                }
                
            }];
            
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
        [self.tableView reloadData];
    }
}
#pragma mark - public

-(void)refresh
{
    [self refreshAndSortView];
}

-(void)refreshDataSource
{
    [self tableViewDidTriggerHeaderRefresh];
}

- (void)isConnect:(BOOL)isConnect{
    if (!isConnect) {
        self.tableView.tableHeaderView = _networkStateView;
    }
    else{
        self.tableView.tableHeaderView = nil;
    }
    
}

- (void)networkChanged:(EMConnectionState)connectionState
{
    if (connectionState == EMConnectionDisconnected) {
        self.tableView.tableHeaderView = _networkStateView;
    }
    else{
        self.tableView.tableHeaderView = nil;
    }
}

//- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
//    NSLog(@"%s",__func__);
//}

@end
